#!/bin/bash

# XY User System 原生部署脚本 (不使用Docker)
# 适用于2核2GB内存服务器的轻量级部署
# 使用方法: ./deploy-native.sh [操作]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置
APP_NAME="xyuser-system"
APP_DIR="/opt/xyuser-system"
APP_USER="xyuser"
NODE_VERSION="18"
MYSQL_VERSION="8.0"
NGINX_CONFIG="/etc/nginx/sites-available/xyuser"
SERVICE_FILE="/etc/systemd/system/xyuser.service"
BACKUP_DIR="/opt/backups"

# 函数定义
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查系统资源
check_system_resources() {
    log_info "检查系统资源..."
    
    # 检查内存
    TOTAL_MEM=$(free -m | awk 'NR==2{printf "%.0f", $2}')
    if [ "$TOTAL_MEM" -lt 1500 ]; then
        log_error "系统内存不足1.5GB，当前: ${TOTAL_MEM}MB"
        exit 1
    fi
    
    # 检查磁盘空间
    DISK_USAGE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
    if [ "$DISK_USAGE" -gt 80 ]; then
        log_warning "磁盘使用率较高: ${DISK_USAGE}%"
    fi
    
    log_success "系统资源检查完成 - 内存: ${TOTAL_MEM}MB, 磁盘使用: ${DISK_USAGE}%"
}

# 安装系统依赖
install_dependencies() {
    log_info "安装系统依赖..."
    
    # 更新系统
    sudo apt update
    
    # 安装基础工具
    sudo apt install -y curl wget git nginx mysql-server-8.0 certbot python3-certbot-nginx
    
    # 安装Node.js
    if ! command -v node &> /dev/null || [ "$(node -v | cut -d'v' -f2 | cut -d'.' -f1)" -lt "$NODE_VERSION" ]; then
        log_info "安装Node.js $NODE_VERSION..."
        curl -fsSL https://deb.nodesource.com/setup_${NODE_VERSION}.x | sudo -E bash -
        sudo apt install -y nodejs
    fi
    
    # 安装PM2
    if ! command -v pm2 &> /dev/null; then
        log_info "安装PM2..."
        sudo npm install -g pm2
    fi
    
    log_success "系统依赖安装完成"
}

# 创建应用用户
create_app_user() {
    log_info "创建应用用户..."
    
    if ! id "$APP_USER" &>/dev/null; then
        sudo useradd -r -s /bin/bash -d $APP_DIR $APP_USER
        sudo mkdir -p $APP_DIR
        sudo chown $APP_USER:$APP_USER $APP_DIR
        log_success "用户 $APP_USER 创建完成"
    else
        log_info "用户 $APP_USER 已存在"
    fi
}

# 配置MySQL
setup_mysql() {
    log_info "配置MySQL数据库..."
    
    # 启动MySQL服务
    sudo systemctl start mysql
    sudo systemctl enable mysql
    
    # 优化MySQL配置（适合2GB内存）
    sudo tee /etc/mysql/mysql.conf.d/xyuser.cnf > /dev/null <<EOF
[mysqld]
# 内存优化配置
innodb_buffer_pool_size = 256M
innodb_log_file_size = 32M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT

# 连接优化
max_connections = 50
thread_cache_size = 8

# 查询缓存
query_cache_size = 32M
query_cache_type = 1

# 其他优化
key_buffer_size = 16M
table_open_cache = 64
sort_buffer_size = 512K
net_buffer_length = 16K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
EOF
    
    # 重启MySQL应用配置
    sudo systemctl restart mysql
    
    # 创建数据库和用户
    sudo mysql -e "CREATE DATABASE IF NOT EXISTS xyuser_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
    sudo mysql -e "CREATE USER IF NOT EXISTS 'xyuser'@'localhost' IDENTIFIED BY 'your_secure_password_here';"
    sudo mysql -e "GRANT ALL PRIVILEGES ON xyuser_db.* TO 'xyuser'@'localhost';"
    sudo mysql -e "FLUSH PRIVILEGES;"
    
    log_success "MySQL配置完成"
}

# 部署应用代码
deploy_app() {
    log_info "部署应用代码..."
    
    # 创建应用目录
    sudo mkdir -p $APP_DIR
    
    # 复制代码到应用目录
    sudo cp -r . $APP_DIR/
    sudo chown -R $APP_USER:$APP_USER $APP_DIR
    
    # 切换到应用用户安装依赖
    sudo -u $APP_USER bash -c "cd $APP_DIR && npm ci --omit=dev"
    
    # 构建应用
    sudo -u $APP_USER bash -c "cd $APP_DIR sudo -u $APP_USER bash -c "cd $APP_DIR && npm run build"sudo -u $APP_USER bash -c "cd $APP_DIR && npm run build" npm run build sudo -u $APP_USER bash -c "cd $APP_DIR && npm run build"sudo -u $APP_USER bash -c "cd $APP_DIR && npm run build" npm run migration:run"
    
    # 创建环境配置文件
    sudo -u $APP_USER tee $APP_DIR/.env > /dev/null <<EOF
NODE_ENV=production
PORT=3000
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=xyuser
DB_PASSWORD=your_secure_password_here
DB_DATABASE=xyuser_db
JWT_SECRET=your_jwt_secret_key_here_please_change_this_in_production
JWT_EXPIRES_IN=7d
UPLOAD_DEST=./public/uploads
MAX_FILE_SIZE=10485760
CORS_ORIGIN=*
LOG_LEVEL=info
APP_BASE_URL=https://your-domain.com
EOF
    
    # 创建上传目录
    sudo -u $APP_USER mkdir -p $APP_DIR/public/uploads
    
    log_success "应用代码部署完成"
}

# 配置PM2
setup_pm2() {
    log_info "配置PM2进程管理..."
    
    # 创建PM2配置文件
    sudo -u $APP_USER tee $APP_DIR/ecosystem.config.js > /dev/null <<EOF
module.exports = {
  apps: [{
    name: 'xyuser-system',
    script: 'dist/main.js',
    cwd: '$APP_DIR',
    instances: 1,
    exec_mode: 'fork',
    max_memory_restart: '512M',
    node_args: '--max-old-space-size=512',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    error_file: '$APP_DIR/logs/err.log',
    out_file: '$APP_DIR/logs/out.log',
    log_file: '$APP_DIR/logs/combined.log',
    time: true,
    autorestart: true,
    watch: false,
    max_restarts: 10,
    min_uptime: '10s'
  }]
};
EOF
    
    # 创建日志目录
    sudo -u $APP_USER mkdir -p $APP_DIR/logs
    
    # 启动应用
    sudo -u $APP_USER bash -c "cd $APP_DIR && pm2 start ecosystem.config.js"
    
    # 保存PM2配置
    sudo -u $APP_USER pm2 save
    
    # 设置PM2开机自启
    sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u $APP_USER --hp $APP_DIR
    
    log_success "PM2配置完成"
}

# 配置Nginx
setup_nginx() {
    log_info "配置Nginx反向代理..."
    
    # 创建Nginx配置
    sudo tee $NGINX_CONFIG > /dev/null <<EOF
server {
    listen 80;
    server_name your-domain.com www.your-domain.com;
    
    # 重定向到HTTPS
    return 301 https://\$server_name\$request_uri;
}

server {
    listen 443 ssl http2;
    server_name your-domain.com www.your-domain.com;
    
    # SSL配置（需要先获取证书）
    # ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
    # ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
    
    # 安全头
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    
    # 客户端最大上传大小
    client_max_body_size 10M;
    
    # 静态文件
    location /public/ {
        alias $APP_DIR/public/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # 代理到Node.js应用
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
        
        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # 健康检查
    location /health {
        proxy_pass http://127.0.0.1:3000/health;
        access_log off;
    }
}
EOF
    
    # 启用站点
    sudo ln -sf $NGINX_CONFIG /etc/nginx/sites-enabled/
    
    # 删除默认站点
    sudo rm -f /etc/nginx/sites-enabled/default
    
    # 测试Nginx配置
    sudo nginx -t
    
    # 启动Nginx
    sudo systemctl start nginx
    sudo systemctl enable nginx
    
    log_success "Nginx配置完成"
}

# 优化系统
optimize_system() {
    log_info "优化系统设置..."
    
    # 创建swap文件（如果不存在）
    if [ ! -f /swapfile ]; then
        log_info "创建1GB swap文件..."
        sudo fallocate -l 1G /swapfile
        sudo chmod 600 /swapfile
        sudo mkswap /swapfile
        sudo swapon /swapfile
        echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
    fi
    
    # 优化内核参数
    sudo tee -a /etc/sysctl.conf > /dev/null <<EOF
# XY User System 优化
vm.swappiness=10
vm.vfs_cache_pressure=50
net.core.rmem_max=16777216
net.core.wmem_max=16777216
net.ipv4.tcp_rmem=4096 87380 16777216
net.ipv4.tcp_wmem=4096 65536 16777216
EOF
    
    sudo sysctl -p
    
    # 设置文件描述符限制
    echo "$APP_USER soft nofile 65536" | sudo tee -a /etc/security/limits.conf
    echo "$APP_USER hard nofile 65536" | sudo tee -a /etc/security/limits.conf
    
    log_success "系统优化完成"
}

# 设置SSL证书
setup_ssl() {
    log_info "设置SSL证书..."
    
    read -p "请输入您的域名: " DOMAIN
    
    if [ -n "$DOMAIN" ]; then
        # 获取Let's Encrypt证书
        sudo certbot --nginx -d $DOMAIN -d www.$DOMAIN
        
        # 设置自动续期
        echo "0 12 * * * /usr/bin/certbot renew --quiet && systemctl reload nginx" | sudo crontab -
        
        log_success "SSL证书设置完成"
    else
        log_warning "跳过SSL证书设置"
    fi
}

# 创建备份脚本
setup_backup() {
    log_info "设置备份策略..."
    
    sudo mkdir -p $BACKUP_DIR
    
    # 创建备份脚本
    sudo tee $APP_DIR/xyuser-backup.sh > /dev/null <<EOF
#!/bin/bash
BACKUP_DATE=\$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/xyuser_backup_\$BACKUP_DATE.sql"

# 备份数据库
mysqldump -u xyuser -pyour_secure_password_here xyuser_db > "\$BACKUP_FILE"

# 压缩备份文件
gzip "\$BACKUP_FILE"

# 删除7天前的备份
find $BACKUP_DIR -name "xyuser_backup_*.sql.gz" -mtime +7 -delete

echo "备份完成: \$BACKUP_FILE.gz"
EOF
    
    sudo chmod +x $APP_DIR/xyuser-backup.sh
    
    # 设置每日备份
    echo "0 2 * * * $APP_DIR/xyuser-backup.sh" | sudo crontab -
    
    log_success "备份策略设置完成"
}

# 完整部署
full_deploy() {
    log_info "开始完整部署..."
    
    check_system_resources
    install_dependencies
    create_app_user
    setup_mysql
    deploy_app
    setup_pm2
    setup_nginx
    optimize_system
    setup_backup
    
    log_success "部署完成！"
    show_status
}

# 更新应用
update_app() {
    log_info "更新应用..."
    
    # 备份数据库
    if [ -f "$APP_DIR/xyuser-backup.sh" ]; then
        $APP_DIR/xyuser-backup.sh
    else
        log_warn "备份脚本不存在，跳过备份步骤"
    fi
    
    # 停止应用
    sudo -u $APP_USER pm2 stop xyuser-system
    
    # 更新代码
    if [ -d ".git" ]; then
        git pull origin master
    fi
    
    # 复制新代码
    sudo cp -r . $APP_DIR/
    sudo chown -R $APP_USER:$APP_USER $APP_DIR
    
    # 安装依赖并构建
    sudo -u $APP_USER bash -c "cd $APP_DIR && npm ci --omit=dev && npm run build"
    
    # 重启应用
    sudo -u $APP_USER pm2 restart xyuser-system
    
    log_success "应用更新完成"
}

# 显示状态
show_status() {
    log_info "系统状态:"
    
    echo "应用状态:"
    sudo -u $APP_USER pm2 status
    
    echo ""
    echo "系统服务状态:"
    sudo systemctl status mysql --no-pager -l
    sudo systemctl status nginx --no-pager -l
    
    echo ""
    echo "资源使用:"
    free -h
    df -h /
    
    echo ""
    echo "访问地址:"
    echo "  - HTTP:  http://localhost"
    echo "  - HTTPS: https://your-domain.com"
    echo "  - 应用:  http://localhost:3000"
}

# 主函数
main() {
    local action=${1:-deploy}
    
    case $action in
        "deploy")
            full_deploy
            ;;
        "update")
            update_app
            ;;
        "start")
            sudo -u $APP_USER pm2 start xyuser-system
            sudo systemctl start nginx mysql
            ;;
        "stop")
            sudo -u $APP_USER pm2 stop xyuser-system
            ;;
        "restart")
            sudo -u $APP_USER pm2 restart xyuser-system
            sudo systemctl restart nginx
            ;;
        "status")
            show_status
            ;;
        "logs")
            sudo -u $APP_USER pm2 logs xyuser-system
            ;;
        "backup")
            if [ -f "$APP_DIR/xyuser-backup.sh" ]; then
                $APP_DIR/xyuser-backup.sh
            else
                log_warn "备份脚本不存在，请先运行部署"
            fi
            ;;
        "ssl")
            setup_ssl
            ;;
        *)
            echo "使用方法: $0 [deploy|update|start|stop|restart|status|logs|backup|ssl]"
            echo ""
            echo "命令说明:"
            echo "  deploy  - 完整部署应用"
            echo "  update  - 更新应用"
            echo "  start   - 启动服务"
            echo "  stop    - 停止应用"
            echo "  restart - 重启应用"
            echo "  status  - 查看状态"
            echo "  logs    - 查看日志"
            echo "  backup  - 备份数据库"
            echo "  ssl     - 设置SSL证书"
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"